package com.sooth.system.user.service;

import cn.hutool.core.collection.CollUtil;
import com.dream.template.mapper.TemplateMapper;
import com.sooth.system.user.mapper.SysUserPostMapper;
import com.sooth.system.user.table.SysUserPost;
import com.sooth.system.user.view.SysUserPostDto;
import com.sooth.system.user.view.SysUserPostVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserPostServiceImpl implements ISysUserPostService {
    private final TemplateMapper templateMapper;

    private final SysUserPostMapper userPostMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysUserPostVo userPostVo) {
        Long userId = userPostVo.getUserId();
        userPostMapper.deleteByUserId(userId);
        List<Long> postIds = userPostVo.getPostIds();
        if (CollUtil.isNotEmpty(postIds)) {
            List<SysUserPost> userPosts = new ArrayList<>(postIds.size());
            for (Long postId : postIds) {
                userPosts.add(new SysUserPost(userId, postId));
            }
            templateMapper.batchInsert(userPosts);
        }
    }

    @Override
    public List<SysUserPost> selectList(SysUserPostDto userPostDto) {
        return templateMapper.selectList(SysUserPost.class, userPostDto);
    }
}
